#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
用户队列管理系统
"""
import sys
import os
import json
from datetime import datetime, timedelta
from typing import Dict, List, Any

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

class UserQueueManager:
    """用户队列管理器"""
    
    def __init__(self):
        self.pending_requests = {}
        self.confirmed_requests = {}
    
    def load_requests(self, pending_requests: Dict, confirmed_requests: Dict):
        """加载请求数据"""
        self.pending_requests = pending_requests
        self.confirmed_requests = confirmed_requests
    
    def get_queue_status(self) -> Dict[str, Any]:
        """获取队列状态"""
        return {
            'pending_count': len(self.pending_requests),
            'confirmed_count': len(self.confirmed_requests),
            'total_count': len(self.pending_requests) + len(self.confirmed_requests),
            'pending_requests': self.pending_requests,
            'confirmed_requests': self.confirmed_requests
        }
    
    def get_pending_users(self) -> List[Dict[str, Any]]:
        """获取待确认用户列表"""
        users = []
        for request_id, data in self.pending_requests.items():
            user_info = data['user_info']
            users.append({
                'request_id': request_id,
                'name': f"{user_info[1]} {user_info[2]}",  # first_name last_name
                'email': user_info[5],
                'service': data['service'],
                'submitted_at': data['timestamp'].isoformat(),
                'status': 'pending',
                'waiting_time': self._calculate_waiting_time(data['timestamp'])
            })
        
        # 按提交时间排序
        users.sort(key=lambda x: x['submitted_at'])
        return users
    
    def get_confirmed_users(self) -> List[Dict[str, Any]]:
        """获取已确认用户列表"""
        users = []
        for request_id, data in self.confirmed_requests.items():
            user_info = data['user_info']
            users.append({
                'request_id': request_id,
                'name': f"{user_info[1]} {user_info[2]}",  # first_name last_name
                'email': user_info[5],
                'service': data['service'],
                'submitted_at': data['timestamp'].isoformat(),
                'confirmed_at': data.get('confirmed_at', '').isoformat() if data.get('confirmed_at') else '',
                'status': data.get('status', 'confirmed'),
                'processing_time': self._calculate_processing_time(data.get('confirmed_at', data['timestamp']))
            })
        
        # 按确认时间排序
        users.sort(key=lambda x: x['confirmed_at'] or x['submitted_at'], reverse=True)
        return users
    
    def get_user_details(self, request_id: str) -> Dict[str, Any]:
        """获取用户详细信息"""
        if request_id in self.pending_requests:
            data = self.pending_requests[request_id]
            user_info = data['user_info']
            return {
                'request_id': request_id,
                'anrede': user_info[0],
                'first_name': user_info[1],
                'last_name': user_info[2],
                'address': user_info[3],
                'zip_code': user_info[4],
                'email': user_info[5],
                'birthday': user_info[6],
                'phone': user_info[7],
                'service': data['service'],
                'submitted_at': data['timestamp'].isoformat(),
                'status': 'pending',
                'waiting_time': self._calculate_waiting_time(data['timestamp'])
            }
        elif request_id in self.confirmed_requests:
            data = self.confirmed_requests[request_id]
            user_info = data['user_info']
            return {
                'request_id': request_id,
                'anrede': user_info[0],
                'first_name': user_info[1],
                'last_name': user_info[2],
                'address': user_info[3],
                'zip_code': user_info[4],
                'email': user_info[5],
                'birthday': user_info[6],
                'phone': user_info[7],
                'service': data['service'],
                'submitted_at': data['timestamp'].isoformat(),
                'confirmed_at': data.get('confirmed_at', '').isoformat() if data.get('confirmed_at') else '',
                'status': data.get('status', 'confirmed'),
                'processing_time': self._calculate_processing_time(data.get('confirmed_at', data['timestamp']))
            }
        else:
            return None
    
    def remove_user(self, request_id: str) -> bool:
        """移除用户（取消申请）"""
        if request_id in self.pending_requests:
            del self.pending_requests[request_id]
            return True
        elif request_id in self.confirmed_requests:
            del self.confirmed_requests[request_id]
            return True
        return False
    
    def get_expired_requests(self, hours: int = 24) -> List[str]:
        """获取过期的请求"""
        expired_requests = []
        cutoff_time = datetime.now() - timedelta(hours=hours)
        
        for request_id, data in self.pending_requests.items():
            if data['timestamp'] < cutoff_time:
                expired_requests.append(request_id)
        
        return expired_requests
    
    def cleanup_expired_requests(self, hours: int = 24) -> int:
        """清理过期的请求"""
        expired_requests = self.get_expired_requests(hours)
        for request_id in expired_requests:
            del self.pending_requests[request_id]
        return len(expired_requests)
    
    def get_statistics(self) -> Dict[str, Any]:
        """获取统计信息"""
        pending_users = self.get_pending_users()
        confirmed_users = self.get_confirmed_users()
        
        # 按服务类型统计
        service_stats = {}
        for user in pending_users + confirmed_users:
            service = user['service']
            if service not in service_stats:
                service_stats[service] = {'pending': 0, 'confirmed': 0}
            if user['status'] == 'pending':
                service_stats[service]['pending'] += 1
            else:
                service_stats[service]['confirmed'] += 1
        
        # 计算平均等待时间
        if pending_users:
            total_waiting_time = sum(user['waiting_time'] for user in pending_users)
            avg_waiting_time = round(total_waiting_time / len(pending_users), 1)
        else:
            avg_waiting_time = 0
        
        return {
            'total_users': len(pending_users) + len(confirmed_users),
            'pending_users': len(pending_users),
            'confirmed_users': len(confirmed_users),
            'service_statistics': service_stats,
            'average_waiting_time': avg_waiting_time,
            'oldest_pending_request': pending_users[0] if pending_users else None
        }
    
    def _calculate_waiting_time(self, submitted_at: datetime) -> int:
        """计算等待时间（分钟）"""
        return int((datetime.now() - submitted_at).total_seconds() / 60)
    
    def _calculate_processing_time(self, confirmed_at: datetime) -> int:
        """计算处理时间（分钟）"""
        return int((datetime.now() - confirmed_at).total_seconds() / 60)

# 主函数已移除 - 这是业务模块，不需要演示代码


